import 'dart:io';
import 'dart:ui' as ui;

import 'package:flutter/cupertino.dart';
import 'package:flutter/rendering.dart';
import 'package:gold/base/view_model.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/xfg_extension.dart';
import 'package:gold/widgets/dialog/permission_dialog.dart';
import 'package:image_gallery_saver_plus/image_gallery_saver_plus.dart';
import 'package:permission_handler/permission_handler.dart';

/// @description:
/// @author tangzhentao
/// @created at 14:57 2024/11/30

class InviteViewModel extends Viewmodel {
  /// 截图key
  final GlobalKey saveKey = GlobalKey();

  /// 保存图片
  Future save() async {
    final pixelRatio = View.of(XfgNav.currentContext).devicePixelRatio;
    final result = await showRequestPermissionDialog(permissions: Platform.isIOS ? [Permission.photos]:[Permission.storage]);
    if (result) {
      final boundary = saveKey.currentContext?.findRenderObject() as RenderRepaintBoundary?;
      final image = await boundary?.toImage(pixelRatio: pixelRatio);
      final byteData = await image?.toByteData(format: ui.ImageByteFormat.png);
      final imageBytes = byteData?.buffer.asUint8List();
      if (imageBytes != null) {
        final save = await ImageGallerySaverPlus.saveImage(imageBytes, quality: 80, name: '先锋金邀请有礼');
        final result = save['isSuccess'] as bool?;
        if (result?? false) {
          '图片已保存至手机/相册'.toast();
        } else {
          '保存失败'.toast();
        }
      } else {
        '获取图片数据失败，请稍后重试'.toast();
      }
    }
  }

  /// 立即邀请
  Future invite() async {

  }
}
